package com.universest.swordholder.data.dao

import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Update
import androidx.room.Delete
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
import kotlinx.parcelize.Parcelize

@Entity(tableName = "book")
data class Book(
    @PrimaryKey(autoGenerate = true) val bookId: Int = 0,
    val bookName: String = "",
    val bookImageSrc: String = "",
    val bookDescription: String = "",
    val bookOrder: Int = 0,
    val bookExtInfo: String = "",
    val charCount: Int = 0,
    val singlePassage: Boolean = false,
    val createTime: Long = System.currentTimeMillis(),
    val lastUpdateTime: Long = System.currentTimeMillis(),
    val lastBrowsePassageId: Int = -1
)

@Dao
interface BookDao {
    @Insert
    suspend fun addBook(book: Book): Long

    @Query("SELECT * FROM book WHERE bookId = :bookId")
    fun getBookById(bookId: Int): Flow<Book?>

    @Query("SELECT * FROM book ORDER BY bookOrder ASC,lastUpdateTime DESC")
    fun getAllBooks(): Flow<List<Book>>

    @Update
    suspend fun updateBook(book: Book)

    @Delete
    suspend fun deleteBook(book: Book)

    @Query("DELETE FROM book WHERE bookId = :bookId")
    suspend fun deleteBookById(bookId: Int)

    @Query("UPDATE book SET lastBrowsePassageId = :passageId WHERE bookId = :bookId")
    suspend fun updateLastBrowsePassageId(bookId: Int, passageId: Int)

    @Query("UPDATE book SET charCount = :charCount WHERE bookId = :bookId")
    suspend fun updateCharCount(bookId: Int, charCount: Int)

    @Query("UPDATE book SET lastUpdateTime = :lastUpdateTime WHERE bookId = :bookId")
    suspend fun updateLastUpdateTime(bookId: Int, lastUpdateTime: Long)
}